package com.yylending.las.webview;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.yyfax.common.CLog;

import java.io.File;

/**
 * Created by HenryZhang on 2016/11/2.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class WebViewSetter {
	private final static String TAG = "WebViewSetter";

	public static boolean shouldOverrideUrlLoading(WebViewActivity aty, String url) {
		CLog.i(TAG, "跳转的url:" + url);
		if (url.startsWith("callfunc://")) {
			return true;
		}
		return false;
	}

	public static void setDownloadListener(final Activity aty, WebView wv) {
		wv.setDownloadListener(new DownloadListener() {
			@Override
			public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
				try {
					Uri uri = Uri.parse(url);
					Intent intent = new Intent(Intent.ACTION_VIEW, uri);
					aty.startActivity(intent);
				} catch (ActivityNotFoundException e) {
					CLog.d(TAG, "had no browser application in device");
				}
			}
		});
	}

	public static void setting(WebViewActivity aty, WebSettings settings) {
		String ua = settings.getUserAgentString();
		settings.setUserAgentString(ua);

		settings.setCacheMode(WebSettings.LOAD_DEFAULT);
		settings.setJavaScriptEnabled(true);
		settings.setAllowFileAccess(true);											//可以访问文件
		settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);	//把所有内容放大等宽的一列中//NARROW_COLUMNS);//适应内容//
		settings.setUseWideViewPort(true);											//是否任意比例缩放
		settings.setLoadWithOverviewMode(true);										//缩放至屏幕的大小
		settings.setSupportZoom(true);												//设置是否支持变焦，false仅支持双击缩放
		settings.setBuiltInZoomControls(true);										//设置是否支持缩放
		settings.setSupportMultipleWindows(false);
		settings.setLoadsImagesAutomatically(true);									//支持自动加载图片
		settings.setNeedInitialFocus(true);											//当webview调用requestFocus时为webview设置节点
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			settings.setDisplayZoomControls(false);
		}
		//settings.setJavaScriptCanOpenWindowsAutomatically(false);					//不支持通过JS打开新窗口
//		settings.setBlockNetworkImage(true);                                        //加载图片放在最后加载渲染

		settings.setRenderPriority(WebSettings.RenderPriority.HIGH);				//提高渲染优先级
		settings.setPluginState(WebSettings.PluginState.ON_DEMAND);
		settings.setDomStorageEnabled(true);
		//to enable local storage enable
		settings.setDatabaseEnabled(true);
		//settings.setDatabasePath(this.getDir("databases", 0).getPath());
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
			File databasePath = aty.getDatabasePath("/data/data/" + aty.getPackageName() + "/databases/");
			settings.setDatabasePath(databasePath.getPath());
		}
		settings.setAppCacheEnabled(true);
		settings.setAppCacheMaxSize(Long.MAX_VALUE);
		settings.setAppCachePath(aty.getDir("cache", Context.MODE_PRIVATE).getPath());
		settings.setGeolocationEnabled(true);
		//settings.setGeolocationDatabasePath(this.getDir("geolocation", 0).getPath());
		// coolpad的手机有点问题，useragent不能包含pad这个单词
		String agent = settings.getUserAgentString();
		CLog.i(TAG, "user agent string : " + agent);
		if (agent.contains("CoolPad")) {
			settings.setUserAgentString(agent.replaceAll("CoolPad", "Xiaomi"));
		}
		if (agent.contains("coolpad")) {
			settings.setUserAgentString(agent.replaceAll("coolpad", "xiaomi"));
		}
		if (agent.contains("COOLPAD")) {
			settings.setUserAgentString(agent.replaceAll("COOLPAD", "XIAOMI"));
		}

		try {
			CookieSyncManager.createInstance(aty);
			CookieSyncManager.getInstance().sync();
		} catch (Exception e) {
		}
	}

	public static void supportChromeDebug(WebView wv) {
		//support chrome debug in computer
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			WebView.setWebContentsDebuggingEnabled(true);
		}
//		if (Build.VERSION.SDK_INT >= 11) {
//			mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
//			mWebView.removeJavascriptInterface("accessibility");
//			mWebView.removeJavascriptInterface("accessibilityTraversal");
//		}
	}

	public static void addJavascriptInterface(WebViewActivity aty, WebView wv, String bridgename) {
		wv.addJavascriptInterface(new WebViewJSObject(aty), bridgename);
	}

	public static void addImageClickListener(WebView wv) {
		// 遍历所有的img点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
		wv.loadUrl(
			"javascript:(function() {" +
				"var objs = document.getElementsByTagName(\"img\");" +
				"for(var i=0;i<objs.length;i++) {" +
					"objs[i].onclick=function() {window.GameHelper.showZoomImage(this.src);}" +
				"}" +
			"})()");
	}
}
